import React, { useState, useEffect, useRef, forwardRef, useImperativeHandle } from 'react';
import Editor from 'wangeditor';
import { Modal, notification } from 'antd';
import PropTypes from 'prop-types';
import imageCompress from '@/utils/imageCompress';
import aliOssUpload from '@/utils/aliOssUpload';
import './style.less';

let editor = '';
function imgToBase64(htmlString) {
  const doc = new DOMParser().parseFromString(htmlString, 'text/html');
  const imgElements = doc.querySelectorAll('img');

  imgElements.forEach((img) => {
    const src = img.getAttribute('src');
    const canvas = document.createElement('canvas');
    const ctx = canvas.getContext('2d');
    const imgObj = new Image();

    imgObj.crossOrigin = 'Anonymous'; // 如果图片需要跨域访问，需要设置这个属性
    imgObj.onload = () => {
      canvas.width = imgObj.width;
      canvas.height = imgObj.height;
      ctx.drawImage(imgObj, 0, 0);
      const base64 = canvas.toDataURL('image/png');
      img.setAttribute('src', base64);
    };

    imgObj.src = src;
  });

  return doc.documentElement.innerHTML;
}

function hasLocalImageTag(str) {
  const imgRegex = /<img[^>]*>/g;
  const localImgRegex = /src="(?!http:\/\/|https:\/\/)[^"]+"/;
  return imgRegex.test(str) && localImgRegex.test(str);
}

// 富文本隐藏的工具栏
const TEXT_SET_TOOL = [
  'todo', // 待办事项
  'quote', // 引用
  'emoticon', // 表情
  // 'video', // 插入视频
  'code', // 插入代码
];

const EditorForm = (
  {
    content,
    initEditor = true,
    maxImgSize = 1000,
    AllImgSize = 5000,
    editClass,
    contentClass,
    editCallback,
    maxLength = 0,
    // dispatch,
  },
  ref,
) => {
  const [initRecord, setInitRecord] = useState(false);
  EditorForm.defaultProps = {
    content: '',
    maxImgSize: 1,
    AllImgSize: 5000,
    editClass: undefined,
    contentClass: undefined,
    maxLength: 0,
  };
  useImperativeHandle(ref || useRef(null), () => {
    return {
      reloadEdit: editorCreate,
    };
  });
  EditorForm.propTypes = {
    content: PropTypes.string,
    maxImgSize: PropTypes.number,
    AllImgSize: PropTypes.number,
    maxLength: PropTypes.number,
    editClass: PropTypes.string,
    contentClass: PropTypes.string,
    editCallback: PropTypes.func.isRequired,
  };
  const getVideoBase64 = (url) => {
    return new Promise(function (resolve, reject) {
      let dataURL = null;
      let video = document.createElement('video');
      video.setAttribute('crossOrigin', 'anonymous');
      video.setAttribute('src', url);
      video.setAttribute('width', 400);
      video.setAttribute('height', 240);
      video.addEventListener('loadeddata', function () {
        let canvas = document.createElement('canvas');
        let width = video.width; //canvas的尺寸和图片一样
        let height = video.height;
        canvas.width = width;
        canvas.height = height;
        canvas.getContext('2d').drawImage(video, 0, 0, width, height); //绘制canvas
        dataURL = canvas.toDataURL('image/jpeg'); //转换为base64
        resolve(dataURL);
      });
    });
  };
  const refEdit = useRef(null);
  // 文本统计
  const [textLength, setTextLength] = useState(0);

  // maxleng存在时超长 编辑区域警告样式
  const maxTextError = textLength > maxLength ? styles.maxlength_box_red : '';

  // maxleng存在时超长 数字警告样式
  const maxNumberError = textLength > maxLength ? styles.maxlength_red : {};

  // 自定义方法
  const customhandle = {
    // 赋值粘贴文本a标签替换
    pasteText: (contents) => {
      const newtext = imgToBase64(contents);
      if (hasLocalImageTag(contents)) {
        notification.warning({
          message: '温馨提示',
          description: '图片粘贴不成功，试试单独复制原图并用Ctrl+V粘贴',
        });
      }
      console.log(imgToBase64(contents));
      return newtext;
    },
    // 自定义提示
    alert: (info) => {
      Modal.info({
        title: info,
      });
    },
    // 自定义图片上传
    uploadImg: (files, insert) => {
      const uploadImgFun = (fileArrs) => {
        aliOssUpload(fileArrs).then((res) => {
          // 上传代码返回结果之后，将图片插入到编辑器中
          res.map((item) => {
            insert(item);
          });
        });
      };
      const fileArr = [];
      // files 是 input 中选中的文件列表
      files.map((item, i) => {
        const fileExtr = item.name.replace(/.+\./, '.').toLowerCase();
        if (fileExtr !== '.gif') {
          imageCompress(item).then(({ file }) => {
            fileArr.push(file);
            if (i === files.length - 1) {
              uploadImgFun(fileArr);
            }
          });
        } else {
          fileArr.push(item);
          if (i === files.length - 1) {
            uploadImgFun(fileArr);
          }
        }
      });
    },
    // 富文本内容修改回调
    change: (html) => {
      if (editCallback) editCallback(html, editor.txt.text());
      if (maxLength !== 0) setTextLength(editor.txt.text().length);
    },
    uploadVideo: (files, insert) => {
      const uploadImgFun = (fileArrs) => {
        aliOssUpload(fileArrs).then((res) => {
          // 上传代码返回结果之后，将图片插入到编辑器中
          res.map((item) => {
            getVideoBase64(item).then((val) => {
              insert(item, val);
            });
          });
        });
      };
      const fileArr = [];
      // files 是 input 中选中的文件列表
      files.map((item, i) => {
        fileArr.push(item);
        if (i === files.length - 1) {
          uploadImgFun(fileArr);
        }
      });
    },
  };
  const editorCreate = () => {
    if (editor) {
      editor.destroy();
      editor = null;
    }
    const elem = refEdit.current;
    editor = new Editor(elem);
    editor.config.excludeMenus = TEXT_SET_TOOL; // 剔除菜单
    editor.config.uploadImgMaxSize = maxImgSize * 1024 * 1024; // 图片大小限制
    editor.config.pasteIgnoreImg = false; // 忽略粘贴内容中的图片
    editor.config.showLinkImg = false; // 隐藏“网络图片”tab
    editor.config.zIndex = 100; // 配置编辑区域的 z-index
    editor.config.height = 550; // 设置编辑区域高度为 500px
    editor.config.uploadImgMaxLength = 20; // 上传图片数量
    editor.config.placeholder = ''; // 不想使用 placeholder ，赋值为空字符串即可
    editor.config.pasteFilterStyle = false; // 过滤掉复制文本的样式
    editor.config.pasteTextHandle = customhandle['pasteText']; // 赋值粘贴文本a标签替换
    editor.config.customUploadImg = customhandle['uploadImg']; // 自定义图片上传
    editor.config.customUploadVideo = customhandle['uploadVideo'];
    editor.config.focus = true;
    editor.config.customAlert = customhandle['alert']; // 自定义提示
    editor.config.onchange = customhandle['change']; // 富文本内容修改回调
    editor.config.showFullScreen = true; // 配置全屏功能按钮是否展示
    editor.config.colors = [
      'rgba(0,0,0,0)',
      '#000000',
      '#FF0000',
      '#00FF00',
      '#00FFFF',
      '#0000FF',
      '#FFFFFF',
      '#CCCCCC',
      '#FFFF00',
      '#FFD700',
      '#F0FFFF',
    ];

    editor.create(); // 初始化
    editor.txt.html(content); // 初始化富文本内容
  };
  useEffect(() => {
    if (initRecord) {
      editorCreate();
    }
  }, [initRecord]);
  useEffect(() => {
    editorCreate();
    setTimeout(() => {
      setInitRecord(true);
    }, 500);
  }, [initEditor]);
  return (
    <div onClick={() => {}} className={`editor ${editClass}`}>
      {/* 编辑区域 */}
      <div ref={refEdit} className={`content ${contentClass} ${maxTextError}`} />
      {/* 数值统计 */}
      {maxLength != 0 && (
        <div style={{ textAlign: 'right' }}>
          <span className={maxNumberError}>{textLength}</span> / {maxLength}
        </div>
      )}
    </div>
  );
};

export default forwardRef(EditorForm);
